function initJPushAndRegister() {
    var ajpush = api.require('ajpush');
    if (api.systemType === 'android' || api.systemType === 'ios') {
        ajpush.init(function (ret) {
            ajpush.getRegistrationId(function (ret, err) {
                jPushRegister(ret.id);
            });
        });
    } else {
        ajpush.getRegistrationId(function (ret) {
            jPushRegister(ret.id);
        });
    }
}

function jPushRegister(registrationId) {
    const params = {
        deviceId: api.deviceId,
        systemType: api.systemType,
        registrationId: registrationId
    }
    fnBodyPost(interfaces.jPushRegister, params, function (ret, err) {

    })
}

//统计-app恢复
function onResume() {
    const ajpush = api.require('ajpush');
    ajpush.onResume();
    console.log('JPush onResume');
}

//统计-app暂停
function onPause() {
    const ajpush = api.require('ajpush');
    ajpush.onPause();
    console.log('JPush onPause');
}

function setDarkStatusBar() {
    api.setStatusBarStyle({
        style: 'dark'
    });
}

function setLightStatusBar() {
    api.setStatusBarStyle({
        style: 'light'
    });
}

function toastBottom(msg) {
    if (msg) {
        api.toast({
            msg: msg,
            location: 'bottom'
        });
    }
}

function toastMiddle(msg) {
    if (msg) {
        api.toast({
            msg: msg,
            location: 'middle'
        });
    }
}

function fixStatusBar() {
    return $api.fixStatusBar($api.dom("header"));
}

function fixTabBar() {
    return $api.fixTabBar($api.dom("footer"));
}

//自定义底部上拉滑块
function showToastUp(el, callback, okBtn, cancelBtn) {
    this.timer = undefined;
    this.showPara = null;
    this.prEl = el;
    this.els = document.querySelector(this.prEl);
    var thisEls = this.els;

    if (!this.els) {
        return false;
    }

    this.clickEl = document.querySelector(this.prEl + ' .obg');
    this.cacheEl = document.querySelectorAll(this.prEl + ' .bt');
    this.opacityBtnEl = document.querySelectorAll(this.prEl + ' .cancelBg');
    this.okEl = this.cacheEl[0];
    this.opacityEl = this.opacityBtnEl[0];

    if (okBtn && document.querySelector(okBtn)) {
        this.okEl = document.querySelectorAll(this.prEl + ' ' + okBtn)[0];
    }

    var that = this;
    this.show = function (paras) {
        that.showPara = paras;
        thisEls.className = 'cmDownToUpWdg showToastUp';
        clearTimeout(this.timer);
        that.timer = setTimeout(function () {
            thisEls.className = 'cmDownToUpWdg showToastUp animatedToastUp';
        }, 5);
    }

    this.cancel = function () {
        thisEls.className = 'cmDownToUpWdg showToastUp';
        clearTimeout(this.timer);
        that.timer = setTimeout(function () {
            thisEls.className = 'cmDownToUpWdg';
        }, 300);
    }

    this.okClose = function () {
        thisEls.className = 'cmDownToUpWdg showToastUp';
        clearTimeout(this.timer);
        that.timer = setTimeout(function () {
            thisEls.className = 'cmDownToUpWdg';
        }, 300);
        callback(thisEls, that.showPara);
    }

    if (this.cacheEl.length == 2) {
        this.cancelBtn = this.cacheEl[1];
        this.cancelBtn && this.cancelBtn.removeEventListener('click', this.cancel, false);
        this.cancelBtn && this.cancelBtn.addEventListener('click', this.cancel, false);
    }

    this.clickEl.removeEventListener('click', this.cancel, false);
    this.okEl && this.okEl.removeEventListener('click', this.okClose, false);
    this.clickEl.addEventListener('click', this.cancel, false);
    this.okEl && this.okEl.addEventListener('click', this.okClose, false);

    this.opacityEl.removeEventListener('click', this.cancel, false);
    this.opacityEl.addEventListener('click', this.cancel, false);

    if (cancelBtn && document.querySelector(cancelBtn)) {
        this.cancelEl = document.querySelectorAll(this.prEl + ' ' + cancelBtn)[0];
        this.cancelEl.removeEventListener('click', this.cancel, false);
        this.cancelEl.addEventListener('click', this.cancel, false);
    }

    return {
        "cancel": this.cancel,
        "show": this.show
    };
}
// 处理日期时间 返回 2020-7-17
function handleTimeYMD2(timestamp) {
    if (!timestamp) {
        return ''
    }
    var date = new Date(timestamp);
    Y = date.getFullYear();
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
    h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours());
    m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
    s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
    return Y + '-' + M + '-' + D
}
// 处理日期时间 返回 2020年7月
function handleTime(timestamp) {
    if (!timestamp) {
        return ''
    }
    var date = new Date(timestamp);
    Y = date.getFullYear();
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
    h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours());
    m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
    s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
    return Y + '年 ' + M + '月'
}

// 处理日期时间Plus
function handleTimePlus(timestamp, status) {
    if (!timestamp) {
        return ''
    }
    var date = new Date(timestamp);
    Y = date.getFullYear();
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
    h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours());
    m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
    s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
    if (status == '//::') {
        return Y + '/' + M + '/' + D + ' ' + h + ':' + m + ':' + s
    } else if (status == '//') {
        return Y + '/' + M + '/' + D
    }
}

// 处理日期时间 返回 2020-07
function handleTimeY_M(timestamp) {
    if (!timestamp) {
        return ''
    }
    var date = new Date(timestamp);
    Y = date.getFullYear();
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
    h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours());
    m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
    s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
    return Y + '-' + M
}

// 处理日期时间 返回 2020/7/17
function handleTimeYMD(timestamp) {
    if (!timestamp) {
        return ''
    }
    var date = new Date(timestamp);
    Y = date.getFullYear();
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
    h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours());
    m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
    s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
    return Y + '/' + M + '/' + D
}

// 处理日期时间 返回 {y:2020,m:11,d:11}
function handleTimeYMobj(timestamp) {
    if (!timestamp) {
        return ''
    }
    var date = new Date(timestamp);
    Y = date.getFullYear();
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
    return {
        y: Y,
        m: M,
        d: D
    }
}

// 处理日期时间 返回 2020年7月17日 15:10:10
function handleTimeYMDHmSZH(timestamp) {
    if (!timestamp) {
        return ''
    }
    var date = new Date(timestamp);
    Y = date.getFullYear();
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
    h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours());
    m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
    s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
    return Y + '年' + M + '月' + D + '日' + ' ' + h + ':' + m + ':' + s
}

// 处理日期时间 返回 2020
function handleTimeY(timestamp) {
    if (!timestamp) {
        return ''
    }
    var date = new Date(timestamp);
    Y = date.getFullYear();
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
    h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours());
    m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
    s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
    return Y
}

function getDateInfo(timestamp) {
    var date = new Date(timestamp);
    return {
        year: date.getFullYear(),
        month: date.getMonth() + 1
    }
}

// 获取年份列表
/**
 *
 * @param {y:2020,m:2} oldYear
 * @param {y:2020,m:11} newYear
 * @param type 0 年 1年月 2年月日
 */
function getYearList(oldYear, newYear, type) {
    var yearList = []
    // 年份列表
    for (var y = oldYear.y; y <= newYear.y; y++) {
        yearList.push({
            id: 1,
            value: y,
            childs: []
        })
    }
    if (type == 1 || type == 2) {
        // 月份列表
        yearList.map(item => {
            if (item.value == oldYear.y && item.value != newYear.y) {
                for (var m = oldYear.m; m <= 12; m++) {
                    item.childs.push({
                        id: 1,
                        value: m,
                        childs: []
                    })
                }
            } else if (item.value == newYear.y && item.value != oldYear.y) {
                for (var m = 1; m <= newYear.m; m++) {
                    item.childs.push({
                        id: 1,
                        value: m,
                        childs: []
                    })
                }
            } else if (item.value == newYear.y && item.value == oldYear.y) {
                for (var m = oldYear.m; m <= newYear.m; m++) {
                    item.childs.push({
                        id: 1,
                        value: m,
                        childs: []
                    })
                }
            } else {
                for (var m = 1; m <= 12; m++) {
                    item.childs.push({
                        id: 1,
                        value: m,
                        childs: []
                    })
                }
            }
        })
    }
    if (type == 2) {
        // 天数列表
        yearList.map(item => {
            item.childs.map(it => {
                var day = new Date(item.value, it.value, 0);
                day = day.getDate()
                if (item.value == oldYear.y && it.value == oldYear.m && item.value == newYear.y && it.value == newYear.m) {
                    var D = oldYear.d
                    var DM = newYear.d
                    for (var d = D; d <= DM; d++) {
                        it.childs.push({
                            id: d,
                            value: d,
                        })
                    }
                } else if (item.value == oldYear.y && it.value == oldYear.m) {
                    var D = oldYear.d
                    for (var d = D; d <= day; d++) {
                        it.childs.push({
                            id: d,
                            value: d,
                        })
                    }
                } else if (item.value == newYear.y && it.value == newYear.m) {
                    var D = newYear.d
                    for (var d = 1; d <= D; d++) {
                        it.childs.push({
                            id: d,
                            value: d,
                        })
                    }
                } else {
                    for (var d = 1; d <= day; d++) {
                        it.childs.push({
                            id: d,
                            value: d,
                        })
                    }
                }
            })
        })
    }
    return yearList
}

/**
 *
 * @param {'年月日列表'} yearList
 * @param {'2020-10-10'} date
 */
function getDateIndex(yearList, date) {
    var nowY = date.slice(0, 4)
    var nowM = date.slice(5, 7)
    var nowD = date.slice(8)
    var indexY = yearList.findIndex(item => {
        return item.value == nowY
    })
    var itemY = yearList.find(item => {
        return item.value == nowY
    })
    var indexM = itemY.childs.findIndex(item => {
        return item.value == nowM
    })
    var itemM = itemY.childs.find(item => {
        return item.value == nowM
    })
    var indexD = itemM.childs.findIndex(item => {
        return item.value == nowD
    })
    return {
        indexY: indexY,
        indexM: indexM,
        indexD: indexD
    }
}

// 上传身份证
function uploadIDCardImg(callback, params) {
    api.actionSheet({
        title: '',
        cancelTitle: '取消',
        buttons: ['拍照', '相册']
    }, function (ret1, err) {
        if (ret1 && (ret1.buttonIndex == 1 || ret1.buttonIndex == 2)) {
            var resultList = api.hasPermission({
                list: ['camera', 'photos']
            });
            if (!resultList[0].granted && !resultList[1].granted) {
                api.requestPermission({
                    list: ['camera', 'photos'],
                }, function (ret, err) {
                    if (ret && ret.list && ret.list.length > 0 && ret
                        .list[0].granted && ret.list[1].granted) {
                        if (ret1.buttonIndex == 1) {
                            return getIdCardPictureUrl('camera', callback, params);
                        } else if (ret.buttonIndex == 2) {
                            return getIdCardPictureUrl('library', callback, params);
                        }
                    }
                });
            } else if (!resultList[0].granted && resultList[1].granted) {
                api.requestPermission({
                    list: ['camera'],
                }, function (ret, err) {
                    if (ret && ret.list && ret.list.length > 0 && ret
                        .list[0].granted) {
                        if (ret1.buttonIndex == 1) {
                            return getIdCardPictureUrl('camera', callback, params);
                        } else if (ret.buttonIndex == 2) {
                            return getIdCardPictureUrl('library', callback, params);
                        }
                    }
                });
            } else if (resultList[0].granted && !resultList[1].granted) {
                api.requestPermission({
                    list: ['photos'],
                }, function (ret, err) {
                    if (ret && ret.list && ret.list.length > 0 && ret
                        .list[1].granted) {
                        if (ret1.buttonIndex == 1) {
                            return getIdCardPictureUrl('camera', callback, params);
                        } else if (ret.buttonIndex == 2) {
                            return getIdCardPictureUrl('library', callback, params);
                        }
                    }
                });
            } else {
                if (ret1.buttonIndex == 1) {
                    return getIdCardPictureUrl('camera', callback, params);
                } else if (ret1.buttonIndex == 2) {
                    return getIdCardPictureUrl('library', callback, params);
                }
            }
        }
    });
}

function getIdCardPictureUrl(sourceType, callback, params) {
    api.getPicture({
        sourceType: sourceType,
        encodingType: 'jpg',
        mediaValue: 'pic',
        destinationType: 'base64',
        allowEdit: false,
        quality: 10,
        saveToPhotoAlbum: false
    }, function (ret, err) {
        if (ret && ret.data && ret.data.length > 0) {
            //上传bas4图片服务器并返回链接
            var spliceBase64 = ret.base64Data.substring(ret.base64Data.indexOf(',') + 1);
            console.log(JSON.stringify(spliceBase64.length / 1024 / 1024));
            fnPost(interfaces.USER_MODULE.AUTHORIZATION.UPLOAD_IDCARDPHOTO, Object.assign({
                "imageBase64": spliceBase64,
                "imageType": ""
            }, params), function (res) {
                callback(res);
            })
        }
    });
}


function upImgCommon(callback) {
    api.actionSheet({
        title: '',
        cancelTitle: '取消',
        buttons: ['拍照', '相册']
    }, function (ret1, err) {
        if (ret1 && (ret1.buttonIndex == 1 || ret1.buttonIndex == 2)) {
            var resultList = api.hasPermission({
                list: ['camera', 'photos']
            });
            if (!resultList[0].granted && !resultList[1].granted) {
                api.requestPermission({
                    list: ['camera', 'photos'],
                }, function (ret, err) {
                    if (ret && ret.list && ret.list.length > 0 && ret.list[0].granted && ret.list[1].granted) {
                        if (ret1.buttonIndex == 1) {
                            return getPictureUrl('camera', callback);
                        } else if (ret1.buttonIndex == 2) {
                            return getPictureUrl('library', callback);
                        }
                    }
                });
            } else if (!resultList[0].granted && resultList[1].granted) {
                api.requestPermission({
                    list: ['camera'],
                }, function (ret, err) {
                    if (ret && ret.list && ret.list.length > 0 && ret.list[0].granted) {
                        if (ret1.buttonIndex == 1) {
                            return getPictureUrl('camera', callback);
                        } else if (ret1.buttonIndex == 2) {
                            return getPictureUrl('library', callback);
                        }
                    }
                });
            } else if (resultList[0].granted && !resultList[1].granted) {
                api.requestPermission({
                    list: ['photos'],
                }, function (ret, err) {
                    if (ret && ret.list && ret.list.length > 0 && ret.list[1].granted) {
                        if (ret1.buttonIndex == 1) {
                            return getPictureUrl('camera', callback);
                        } else if (ret1.buttonIndex == 2) {
                            return getPictureUrl('library', callback);
                        }
                    }
                });
            } else {
                if (ret1.buttonIndex == 1) {
                    return getPictureUrl('camera', callback);
                } else if (ret1.buttonIndex == 2) {
                    return getPictureUrl('library', callback);
                }
            }
        }
    });
}

function getPictureUrl(sourceType, callback) {
    api.getPicture({
        sourceType: sourceType,
        encodingType: 'jpg',
        mediaValue: 'pic',
        destinationType: 'base64',
        allowEdit: false,
        quality: 80,
        saveToPhotoAlbum: false
    }, function (ret, err) {
        if (ret && ret.data && ret.data.length > 0) {
            //上传bas4图片服务器并返回链接
            var spliceBase64 = ret.base64Data.substring(ret.base64Data.indexOf(',') + 1);
            fnPostUpData(interfaces.CONTENT_MODULE.UPLOAD_IMAGE, {
                base64Image: spliceBase64
            }, true, function (res) {
                callback(res);
            })
        }
    });
}

// 一键登入
function oneClickLogin(params, callback) {
    api.showProgress({
        title: '小蟹加载中...',
        text: '',
        modal: true
    });
    //检查当前环境是否支持一键登录
    let aliATAuth = api.require('aliATAuthZiZhu');
    aliATAuth.checkEnvAvailable(function (ret) {
        if (ret.enable) {
            // 支持一键登入
            // 调起授权页面
            aliATAuth.getLoginTokenFullScreen(params, function (ret) {
                console.log('一键登录', JSON.stringify(ret));
                api.hideProgress();
                if (ret.resultCode == 600001) {
                    // 600001调起页面成功
                }
                if (ret.resultCode == 600000) {
                    // 600000获取到token
                    // 请求接口
                    var param = {
                        accessToken: ret.token,
                        authType: 'ONE_KEY',
                        platformType: 'APP',
                        operationType: 'LOGIN'
                    }
                    common("onKeyLogin")(param, function (ret) {
                        aliATAuth.hideLoginLoading();
                        if (ret.code === 20000) {
                            $api.setStorage('accessToken', ret.data)
                            api.setPrefs({
                                key: 'accessToken',
                                value: ret.data
                            });
                            callback('success')
                            // 关闭一键登入页面
                            aliATAuth.cancelLoginVC();
                        } else {
                            // 一键登入失败
                            // 关闭一键登入页面,跳转普通登入
                            aliATAuth.cancelLoginVC();
                            callback('fail')
                        }
                    });
                    aliATAuth.cancelLoginVC();
                } else if (ret.resultCode == 600002 || ret.resultCode == 600005 || ret.resultCode == 600011 || ret.resultCode == 600015 || ret.resultCode == 600021 || ret.resultCode == 700001) {
                    aliATAuth.cancelLoginVC();
                    // 一键登入失败转普通登录
                    callback('fail')
                } else if (ret.resultCode == 700002){
                    // toastMiddle('请阅读并同意用户隐私') 无用
                }
            });
        } else {
            // 不支持一键登入转普通登入
            api.hideProgress();
            callback('fail')
        }
    });
}

/**
 * 高德地图两点间距离计算函数
 * @param  lat  经度
 * @param  lon  纬度
 */

function getDistance(lat1, lon1, lat2, lon2) {
    var radLat1 = (lat1 * Math.PI) / 180; //将角度换算为弧度
    var radLat2 = (lat2 * Math.PI) / 180; //将角度换算为弧度
    var a = radLat1 - radLat2;
    var b = (lon1 * Math.PI) / 180 - (lon2 * Math.PI) / 180;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(
        Math.sin(b / 2), 2)));
    s = s * 6378137.0; // 取WGS84标准参考椭球中的地球长半径(单位:m)
    //s = Math.round(s * 10000) / 10000; //两点之间距离(保留四位)
    return s; //(单位:m)
}

/**
 * 距离保留两位小数
 */
function distanceEclipse(distance) {
    distance += ""
    var regex = /([0-9]+).[0-9]*/;
    // var regex = /([0-9]+.[0-9]{2})[0-9]*/;
    return distance.replace(regex, "$1")
}

/**
 * 打开地图导航
 */
// 打开地图
function openMap(location, address) {
    var vm = this;
    var systemType = api.systemType;
    var buttons = new Array();
    var amap_installed = false;
    if (systemType == 'ios') {
        var installed = api.appInstalled({
            sync: true,
            appBundle: 'iosamap'
        });
        if (installed) {
            amap_installed = true;
            buttons.push('高德地图');
        }
    } else {
        var installed = api.appInstalled({
            sync: true,
            appBundle: 'com.autonavi.minimap'
        });
        if (installed) {
            amap_installed = true;
            buttons.push('高德地图');
        }
    }
    if (amap_installed == false) {
        api.toast({
            msg: '您没有安装高德地图'
        });
        return false;
    }
    api.confirm({
        title: '是否打开高德APP',
        buttons:['确定', '取消']
    },function(ret,err){
        if(ret.buttonIndex == 1){
            toGaode(location, address)
        }
    });
    // api.actionSheet({
    //     cancelTitle: '取消',
    //     buttons: buttons
    // }, function (ret, err) {
    //     var btnIndex = ret.buttonIndex;
    //     if (btnIndex == 1) {
    //         if (amap_installed) {
    //             api.confirm({
    //                 title: '是否打开',
    //                 msg: 'msg',
    //                 buttons:['确定', '取消']
    //             },function(ret,err){
    //                 if(ret.buttonIndex == 1){
    //                     api.alert({msg: '点击了确定'});
    //                 }
    //             });
    //             toGaode(location, address)
    //         }
    //     }
    // });
}

function toGaode(location, address) {
    var lon = location.lon
    var lat = location.lat
    if (api.systemType == 'ios') {
        api.openApp({
            iosUrl: 'iosamap://path?sourceApplication=applicationName&sid=BGVIS1&did=BGVIS2&dlat=' + lat + '&dlon=' + lon + '&dname=' + address + '&dev=0&t=0',
        }, function (ret, err) {});
    } else {
        api.openApp({
            androidPkg: 'android.intent.action.VIEW',
            uri: 'amapuri://route/plan/?dlat=' + lat + '&dlon=' + lon + '&dname=' + address + '&dev=0&t=0'
        }, function (ret, err) {});
    }
}

/**
 * 检查是否被收藏，如果被 收藏，则设置vm中的isCollect属性为true
 * @param module module
 * @param id id
 * @param vm 必传
 */
function checkHasCollect(module, id, vm) {
    common('checkHasCollect')({
        module: module,
        moduleMediaId: [id]
    }, function (ret) {
        vm.isCollect = ret.data.indexOf(id) !== -1;
    })
}

/**
 * 添加浏览记录
 * @param module module
 * @param id id
 */
function addBrowse(module, id) {
    common('addBrowse')({
        module: module,
        moduleMediaId: id
    }, function (ret) {});
}

/**
 * 改变收藏状态
 * @param module module
 * @param id id
 * @param vm 必传，且必须有isCollect属性
 */
function handleCollect(module, id, vm) {
    if (!module) {
        return;
    }
    var param = {
        favorite: !vm.isCollect,
        module: module,
        moduleMediaId: id
    }
    if (!vm.isCollect) {
        common("addCollect")(param, function (ret) {
            toastMiddle("收藏成功，可在“我的收藏”中查看")
            vm.isCollect = !vm.isCollect;
        })
    } else {
        common("cancelCollect")(param, function (ret) {
            toastMiddle("取消收藏，已经从“我的收藏”中移除")
            vm.isCollect = !vm.isCollect;
        })
    }
}

function toReportOrShareDialog(module, id, type, description, topicType, userInfo) {
    api.openFrame({
        name: 'report_alert',
        url: 'widget://html/common/report_alert_frm.html',
        rect: {
            marginTop: 0,
            marginBottom: 0,
            w: 'auto',
        },
        pageParam: {
            id: id,
            type: type,
            module: module,
            description: description,
            topicType: topicType || '',
            userInfo: userInfo || '',
        }
    })
}

/**
 * 图片预览功能
 * @param index 图片索引
 * @param medias 图片数组
 * @param photoBrowser 预览模块对象
 */
function previewPhoto(index, medias, photoBrowser) {
    var images = []
    medias.map(item => {
        if (item.imagePath || item.imagePath === '') {
            images.push(item.imagePath)
        } else if (item.imageUrl || item.imageUrl === '') {
            images.push(item.imageUrl)
        }
    })
    photoBrowser.open({
        images: images,
        activeIndex: index,
        // placeholderImg: 'widget://image/default/item_img.png',
        bgColor: '#000'
    }, function (ret, err) {
        if (ret.eventType == 'click') {
            photoBrowser.close();
        }
    });
}

function gIMCommon(userId) {
    common('getShopKfUrl')(userId, function (ret) {
        if (ret.data) {
            api.openWin({
                name: 'IM_win',
                url: 'widget://html/IM/IM_win.html',
                bounces: false,
                pageParam: {
                    kfUrl: ret.data.kfUrl,
                }
            });
        }
    })
}


/**
 * 图片懒加载
 */
function imgLazyLoad() {
    // api.clearCache();
    const imageCacheKey = location.href;
    var imageCacheValue = api.getPrefs({
        sync: true,
        key: imageCacheKey
    });
    imageCacheValue = imageCacheValue ? JSON.parse(imageCacheValue) : null;
    // imageCacheValue = null
    if (!imageCacheValue || !imageCacheValue.expireTime || imageCacheValue.expireTime < new Date().getTime()) {
        imageCacheValue = {
            expireTime: new Date().getTime() + 60 * 60 * 24 * 7 * 1000,
            imageCacheValues: {}
        };
        api.setPrefs({
            key: imageCacheKey,
            value: JSON.stringify(imageCacheValue)
        });
    }
    Vue.use(VueLazyload, {
        error: 'widget://image/default/loading3.png',
        loading: 'widget://image/default/loading3.png',
        attempt: 1,
        filter: {
            progressive(listener, options) {
                if (listener.src) {
                    const originalUrl = listener.src;
                    let cacheUrl = imageCacheValue.imageCacheValues[originalUrl];
                    if (cacheUrl) {
                        listener.src = cacheUrl;
                        // console.log('使用缓存', JSON.stringify(cacheUrl))
                    } else {
                        api.imageCache({
                            url: originalUrl,
                            policy: 'default',
                            thumbnail: false
                        }, function (ret, err) {
                            // console.log('缓存结果:', JSON.stringify(ret))
                            if (ret.status) {
                                cacheUrl = ret.url;
                                console.log('URL:', JSON.stringify(ret.url));
                                imageCacheValue.imageCacheValues[originalUrl] = cacheUrl;
                                api.setPrefs({
                                    key: imageCacheKey,
                                    value: JSON.stringify(imageCacheValue)
                                });
                                // console.log('进行缓存到map中')
                            } else {
                                // console.log('缓存失败')
                            }

                        })
                        // console.log('继续使用原url')
                    }
                }
            },
        }
    })
}

/**
 *
 * @param {价格} price
 * @returns
 */
function filterPrice(price) {
    if (price === null || price === '') {
    return '面议'
    } else if (Number(price) > 10000) {
    
    return (Math.floor(Number(price) / 10000 * 100) / 100).toFixed(2) + '万'
    } else {
    return Number(String(price).toString().match(/^\d+(?:\.\d{0,2})?/)).toFixed(2)
    }
}

function doSoftInput(vm) {
    var win_h = api.winHeight;
    window.addEventListener('resize', function () {
        if (api.winHeight < win_h) {
            vm.isSubmit = false
        } else {
            vm.isSubmit = true
        }
    });
}

function getObjectURL(file) {
    var url = null;
    if (window.createObjectURL != undefined) {
        url = window.createObjectURL(file);
    } else if (window.URL != undefined) {
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) {
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}

function filterText(text) {
    if (text.length >= 7) {
        text = text.substr(0, 5) + '...'
    }
    return text
}

function throttle(fn, interval) {
    var enterTime = 0;//触发的时间
    var gapTime = interval || 300 ;//间隔时间，如果interval不传，则默认300ms
    return function() {
      var context = this;
      var backTime = new Date();//第一次函数return即触发的时间
      if (backTime - enterTime > gapTime) {
        fn.call(context,arguments);
        enterTime = backTime;//赋值给第一次触发的时间，这样就保存了第二次触发的时间
      }
    };
  }

function requestPermission(){
    var resultList = api.hasPermission({
        list: ['camera', 'photos']
    });
    if(resultList[0].granted){
        return true
    }else{
        api.requestPermission({
            list: ['camera', 'photos'],
        }, function (ret, err) {
            if (ret && ret.list && ret.list.length > 0 && ret.list[0].granted && ret.list[1].granted) {
                return true
            }else{
                return false
            }
        });
    }
}

// 拍照
function commonDoPic(callback){
    api.getPicture({
        sourceType: 'camera',
        encodingType: 'jpg',
        mediaValue: 'pic',
        destinationType: 'base64',
        allowEdit: false,
        quality: 80,
        saveToPhotoAlbum: false
    }, function (ret, err) {
        if (ret && ret.data && ret.data.length > 0) {
            api.showProgress({
                title: '小蟹上传中...',
                text:'(1/1)'
            });
            var spliceBase64 = ret.base64Data.substring(ret.base64Data.indexOf(',') + 1);
            fnPostUpData(interfaces.CONTENT_MODULE.UPLOAD_IMAGE, {
                base64Image: spliceBase64
            }, false, function (res) {
                if (res && res.code === RESPONSE_OK) {
                    api.hideProgress();
                    toastMiddle('上传成功');
                    res.data.showImagePath = ret.base64Data
                    callback(res);
                } else {
                    api.hideProgress();
                    toastMiddle(res ? res.msg : '');
                }
            })
        }
    });
}

// 摄像
function commonDoCamera(type, callback){
    api.getPicture({
        sourceType: 'camera',
        encodingType: 'jpg',
        mediaValue: 'video',
        destinationType: 'url',
        allowEdit: false,
        quality: 80,
        saveToPhotoAlbum: false
    }, function (ret, err) {
        if(ret && ret.data){
            var queryParam = {
                file:ret.data
            }
            var queryValues = {
                type:type
            }
            api.showProgress({
                title: '小蟹上传中...',
                text:'(1/1)'
            });
            fnBodyPostFile(interfaces.CONTENT_MODULE.UPLOAD_VIDEO,queryParam,queryValues,false,function(res){
                if (res && res.code === RESPONSE_OK) {
                    api.hideProgress();
                    toastMiddle('上传成功');
                    callback(res, queryParam);
                } else {
                    api.hideProgress();
                    toastMiddle(res ? res.msg : '');
                }
            })
        }
    });
}

// 相册
function commonDoLibrary( libraryType, type, callback, libraryTypeMax){
    var UIAlbumBrowser = api.require('UIAlbumBrowser');
    UIAlbumBrowser.open({
        max: libraryTypeMax || 9,
        type:libraryType,
        selectedAll:true,
        alertTitle: libraryType === 'all' ? '你最多只能选择'+ (libraryTypeMax || 9) + '个视频或照片' : (libraryType === 'video' ? '你最多只能选择'+ (libraryTypeMax || 9) + '个视频': '你最多只能选择'+ (libraryTypeMax || 9) + '个照片'),
        styles: {
            bg: '#fff',
            mark: {
                icon: '',
                position: 'bottom_left',
                size: 20
            },
            nav: {
                bg: 'rgba(0,0,0,0.6)',
                titleColor: '#fff',
                titleSize: 18,
                cancelColor: '#fff',
                cancelSize: 16,
                finishColor: '#fff',
                finishSize: 16
            }
        },
        rotation: true
    }, function(ret) {
        if(ret && ret.list && ret.list.length > 0){
            var listFile =  ret.list;
            if(api.systemType == 'ios'){
                listFile = listFile.reverse()
            }
            commonUploadRepeat(listFile, type, callback)
        }
    });
}      

var  multipleFileCount = 0
function commonUploadRepeat(files,type,callback){
    // console.log(JSON.stringify(files));
    // console.log(JSON.stringify(multipleFileCount));
    api.showProgress({
        title: '小蟹上传中...',
        text: (multipleFileCount + 1) + '/' + files.length
    });
    if(files.length > multipleFileCount){
        commonUploadMultipleFile(files, type, callback)
    }else{
        multipleFileCount = 0
        api.hideProgress();
        toastMiddle('上传成功');
    }
}

function commonUploadMultipleFile (files, type, callback){
    var queryValues ={
        type:type
    }
    if(api.systemType == 'ios'){
        console.log(JSON.stringify(files[multipleFileCount]));
        var UIAlbumBrowser = api.require('UIAlbumBrowser');
        if(files[multipleFileCount].mediaType == 'video'){
            UIAlbumBrowser.transVideoPath({
                path: files[multipleFileCount].path
            }, function(ret1, err1) {
                if (ret1) {
                    var queryParam = {
                        file:ret1.albumVideoPath
                    }
                    fnBodyPostFile(interfaces.CONTENT_MODULE.UPLOAD_VIDEO, queryParam, queryValues, false, function(ret2){
                        if (ret2 && ret2.code === RESPONSE_OK) {
                            callback(ret2, queryParam, files[multipleFileCount].mediaType);
                            multipleFileCount++
                            commonUploadRepeat(files, type, callback)
                        } else {
                            multipleFileCount = 0
                            api.hideProgress();
                            toastMiddle(ret2 ? ret2.msg : '');
                        }
                    })
                }
            });
        }else{
            UIAlbumBrowser.transPath({
                path: files[multipleFileCount].path
            }, function(ret1, err) {
                if (ret1) {
                    var queryParam = {
                        file:ret1.path
                    }
                    fnBodyPostFile(interfaces.CONTENT_MODULE.UPLOAD_IMAGE_PART,queryParam,{},false,function(ret2){
                        if (ret2 && ret2.code === RESPONSE_OK) {
                            ret2.data.showImagePath = queryParam.file
                            callback(ret2, queryParam, files[multipleFileCount].mediaType);
                            multipleFileCount++
                            commonUploadRepeat(files, type, callback)
                        } else {
                            multipleFileCount = 0
                            api.hideProgress();
                            toastMiddle(ret2 ? ret2.msg : '');
                        }
                    })
                }
            });
        }
    }else{
        files[multipleFileCount].mediaType = files[multipleFileCount].suffix === 'mp4' ? 'video' : 'image'
        if(files[multipleFileCount].mediaType == 'video'){
            var queryParam = {
                file:files[multipleFileCount].path
            }
            fnBodyPostFile(interfaces.CONTENT_MODULE.UPLOAD_VIDEO, queryParam, queryValues, false, function(ret2){
                if (ret2 && ret2.code === RESPONSE_OK) {
                    callback(ret2, queryParam, files[multipleFileCount].mediaType);
                    multipleFileCount++
                    commonUploadRepeat(files, type, callback)
                } else {
                    multipleFileCount = 0
                    api.hideProgress();
                    toastMiddle(ret2 ? ret2.msg : '');
                }
            })
        }else{
            var queryParam = {
                file:files[multipleFileCount].path
            }
            fnBodyPostFile(interfaces.CONTENT_MODULE.UPLOAD_IMAGE_PART,queryParam,{},false,function(ret2){
                if (ret2 && ret2.code === RESPONSE_OK) {
                    ret2.data.showImagePath = queryParam.file
                    callback(ret2, queryParam, files[multipleFileCount].mediaType);
                    multipleFileCount++
                    commonUploadRepeat(files, type, callback)
                } else {
                    multipleFileCount = 0
                    api.hideProgress();
                    toastMiddle(ret2 ? ret2.msg : '');
                }
            })
        }
    }
}

// function decryptAuth(encrypted) {
//     //公钥
//     const PUBLIC_KEY = "MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQDk881j26qATtsY55Y10DPZsRAPfnn3xm7UIC48ArvrEjwnes5MbLCtvDnSUvceLcU5mbUzlVGPj/64N/FvrgoYYAon8DUUnw1MblsFdl9yW1eGwhBcLfs31a1iZiyFiyT0wlVy78o6hv4sAqN52lmOjsHvCHaoAFmvZgdoNKDJB974DhkHJmR5uJv78ouyyPDqR5xdBt3PW9xR2KC7wXWoufDSD7zhHgb0TfB93JVCjz9vwXN+2vNIZBrglLURoPRyD5C0vaCazgwAG8zdQ699iw/BNNudb4CeOirnvKGaXz5azkKRAHK6PuWbodviXffjxTYq9WTtANkY5NOvQq9HQIETC2XnWeJs3qfBuOLpUKcpmn8XxRsZ3R/+SRs24r/aenrRCGDtpkS4ksKfknOGZtOr4NXz7SV4C9kL7sDXGzIqEr2YR++fLeoBhd7wBh4Kw0SO3x6x3z50maepIthqGH1Jo30+7Bxi0JYTcgd/7ZTWxXQ1TvFhtvW7qHTB1wY5ZybnZXsDWlhojxYrQr0mseUqnT8GCTrxHdnduPm71aIc+O3DMC3GVPFKhcG9E0epqsa5PEg2iTYMipPIdDi8eU3KJqQjTodW1rQuIAf1vd0YkTGjfmZEXrmNsZSZu7nggeXWUjAo/eKeZKsIl3oC8ke6GaycwQ3TMs2d8m5bRwIDAQABAoICABupURFVgt4JqPLzV/SceQc+G0Cj+Tx0XwOF99AMTIP0KgxjC/Wz1AzJhvr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lgwdVfHpWkqOdUY8RAUO3xx6xHhZACaGFhpS95ODBACZQx2RAumE8kJaLsYuG3FxJvfmaQkypGca885Na5tcqcFcKrAPFeKhzahXwu2vKT0rErOT5q4Z9FlsH6tyUUTLUUAvURSzkGEDkoENHMgqJ+kwtHts1le9GHd10n2xAnax723rKR5gE44WUvBH4Q=="
//     //使用私钥解密
//     var decrypt = new JSEncrypt();
//     decrypt.setPrivateKey('-----BEGIN PRIVATE KEY-----' + PUBLIC_KEY + '-----END PRIVATE KEY-----');
//     return decrypt.decrypt(encrypted)
// }

// 滚动加载
function scrollToBottom(){
    let scrollTimeout;
    return function scrollThrottler(e, callback) {
        if (!scrollTimeout) {
            scrollTimeout = setTimeout(function () { // 减少scroll执行频率
                scrollTimeout = null;
                if((e.target.scrollTop + e.target.clientHeight) >= (e.target.scrollHeight - 60)) {
                    callback(); // 当到达接近底部时, 触发回掉函数
                }
            }, 66);
        }
    }
}

//百度统计页面开始
function setBDPageStart(pageName){
    var baidu = api.require('modulebaidumtj');
    baidu.onPageStart({
        pageName: pageName
    })
}

//百度统计页面结束
function setBDPageEnd(pageName){
    var baidu = api.require('modulebaidumtj');
    baidu.onPageEnd({
        pageName: pageName
    })
}